// 文件：src/utils/buildDynamicRoutes.ts

// import type { RouteRecordRaw } from "vue-router";
import { type MenuItem } from "@/types/route";
import Layout from "@/layout/index.vue";

// 构建动态路由
export function buildDynamicRoutes(data: MenuItem[], source: any) {
  const modules = import.meta.glob("@/views/**/*.vue");

  data.forEach((item: MenuItem) => {
    const route: MenuItem = {
      id: item.id,
      pid: item.pid,
      path: item.path,
      name: item.name,
      meta: item.meta,
      children: []
    };

    if (item.pid === 0) {
      // 根菜单
      route.component = Layout;
    } else if (item.meta.type === 4 || !item.component) {
      // 当路由为目录或者没有组件时
      route.component = undefined;
    } else if (item.component) {
      const viewPath = `/src/views${item.component}.vue`;
      if (modules[viewPath]) {
        route.component = modules[viewPath];
      } else {
        console.warn(`未找到页面组件: ${viewPath}`);
        route.component = undefined;
      }
    } else {
      route.component = undefined;
    }
    // 判断是否有子菜单
    if (item.children && item.children.length) {
      this.buildDynamicRoutes(item.children, route.children);
    }
    source.push(route);
  });
}

// 过滤可见菜单
export function filterVisibleMenus(menus: MenuItem[]): MenuItem[] {
  // 使用 reduce 方法遍历菜单项
  return menus.reduce((acc, menu) => {
    // 先做基础过滤判断
    if (menu.meta?.is_hidden === 1 || menu.path === "/login") {
      return acc; // 剔除
    }

    // 如果是 layout 类型，只处理 children，自身不加入结果
    if (menu.name === "layout") {
      const children = menu.children ? this.filterVisibleMenus(menu.children) : [];
      acc.push(...children); // 把 children 提升一级加入结果
      return acc;
    }

    // 普通菜单项：递归处理自己的 children
    const filteredMenu = {
      ...menu,
      children: menu.children ? this.filterVisibleMenus(menu.children) : []
    };

    acc.push(filteredMenu);
    return acc;
  }, [] as MenuItem[]);
}

// 获取第一个有效子路由
export function findFirstValidPath(items: MenuItem[]): string | null {
  for (const item of items) {
    if (!item.meta) continue;
    if (item.component && item.meta.type === 1 && item.meta.is_hidden == 2) {
      return item.path || null;
    } else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      const result = this.findFirstValidPath(item.children);
      if (result) return result;
    }
  }
  return null;
}

// 获取当前路由路径（兼容 hash/history 模式）
export function getCurrentPath(): string {
  const { hash, pathname } = window.location;
  if (hash.startsWith("#/")) {
    return hash.slice(1); // 去掉 #
  }
  return pathname;
}
